package com.yang.booking.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yang.booking.config.JwtTokenConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureException;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private JwtTokenConfig jwtTokenConfig ;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws SignatureException, IOException {
        /** 地址过滤 */
        String uri = request.getRequestURI() ;
        if (uri.contains("/provider/user/sing")){
            return true ;
        }

        /** Token 验证 */
        String token_str = request.getHeader(jwtTokenConfig.getHeader());

        if(StringUtils.isEmpty(token_str)){
            token_str = request.getParameter(jwtTokenConfig.getHeader());
        }

        if(StringUtils.isEmpty(token_str)){

            response.setHeader("Content-Type", "application/json");
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> msg = new HashMap<String,Object>();
            msg.put("massage", jwtTokenConfig.getHeader()+ "不能为空");
            msg.put("code", 400);
            response.getWriter().write(JSONObject.toJSONString(msg));

            return false;

//            throw new SignatureException(jwtConfig.getHeader()+ "不能为空");
        }

        String[] token_list = token_str.split(" ");
        if(token_list.length < 2){

            response.setHeader("Content-Type", "application/json");
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> msg = new HashMap<String,Object>();
            msg.put("massage", jwtTokenConfig.getHeader()+ "token格式不对");
            msg.put("code", 400);
            response.getWriter().write(JSONObject.toJSONString(msg));

            return false;

//            throw new SignatureException(jwtConfig.getHeader()+ "不能为空");
        }

        if(!token_list[0].equals("Bearer")){

            response.setHeader("Content-Type", "application/json");
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> msg = new HashMap<String,Object>();
            msg.put("massage", jwtTokenConfig.getHeader()+ "token头错误");
            msg.put("code", 400);
            response.getWriter().write(JSONObject.toJSONString(msg));

            return false;

//            throw new SignatureException(jwtConfig.getHeader()+ "不能为空");
        }

        Claims claims = null;
        try{
            claims = jwtTokenConfig.getClaimByToken(token_list[1]);
            if(claims == null || jwtTokenConfig.isTokenExpired(claims.getExpiration())){

                response.setHeader("Content-Type", "application/json");
                response.setContentType("application/json;charset=UTF-8");
                Map<String, Object> msg = new HashMap<String,Object>();
                msg.put("massage", jwtTokenConfig.getHeader()+ "失效，请重新登录。");
                msg.put("code", 400);
                response.getWriter().write(JSONObject.toJSONString(msg));

                return false;
//                throw new SignatureException(jwtConfig.getHeader() + "失效，请重新登录。");
            }
        }catch (Exception e){

            response.setHeader("Content-Type", "application/json");
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> msg = new HashMap<String,Object>();
            msg.put("massage", jwtTokenConfig.getHeader()+ "失效，请重新登录。");
            msg.put("code", 400);
            response.getWriter().write(JSONObject.toJSONString(msg));

            return false;
//            throw new SignatureException(jwtConfig.getHeader() + "失效，请重新登录。");
        }

        /** 设置 identityId 用户身份ID */
        request.setAttribute("identityId", claims.getSubject());
        return true;
    }

}
